<?php

/**
* Class wich manages languages on Babili
*/
class BabiliLanguage {
	
	//the db connector
	private $db;
	
	/**
	 * The construct load the db connector
	 * @param $db
	 */
	public function __construct($db){
		$this->db = $db;
	}
	/**
	 * Add language to Babili
	 * @param $name
	 * @param $label
	 * @param $country_code
	 * @param $language_code
	 * @param $flag
	 * @return $id_language, false else
	 */
	public function add($name, $label, $country_code, $language_code, $flag){
		
		//if there is a missing argument return false
		if(empty($name) || empty($label) || empty($country_code) || empty($language_code) || empty($flag)){
			return false;
		}
		
		//insert in database
		$query = "INSERT INTO language (name, label, country_code, language_code, flag)
				  VALUES (:name, :label, :country_code, :language_code, :flag )";
		$query_args = array(':name' => $name,
							':label' => $label,
							':country_code' => $country_code,
							':language_code' => $language_code,
							':flag' => $flag);
		
		if($this->db->update($query, $query_args)){
			//return the id
			return $this->db->last_id();			 
		}

	}
	
	/**
	 * Remove language of Babili
	 * @param $id_language
	 * @return bool true if successful delete, false else
	 */
	public function delete($id_language){
		
		if(empty($id_language))
			return false;
		
		$query = "DELETE FROM language WHERE id = :id_language";
		
		$query_args = array(':id_language' => $id_language);
		
		return $this->db->update($query, $query_args);
		
	}
	
	/**
	 * Get informations about language
	 * @param $id_language can be the id (so integer) or the ISO code (string with 2 caracters)
	 * @return array('name' => $name, 'label' => $label, 'country_code' => $code, 'language_code' => $language_code, 'flag' => $flag)
	 * 		   false if any errors
	 */
	public function get($id_language){
		
		if(empty($id_language) || (!is_numeric($id_language) && !is_string($id_language)))
			return false;
		
		$query = "SELECT * FROM language WHERE ";
		
		if(is_numeric($id_language)){
			$query .= "id = :id_language";
		}else{
			//it's a string, so country code
			$query .= "country_code = :id_language";
		}
		
		$query_args = array(':id_language' => $id_language);
		
		$language = $this->db->select($query, $query_args);
		
		if($language)
			//the select method return an array, even if there is one result, return the first element
			return reset($language);
		else
			return false;
		
	}
	
	/**
	 * Get all languages of Babili
	 * @return array($id_language => array('name' => $name, 'label' => $label, 'code' => $code, 'flag' => $flag),
	 * 				 $id_language2 => array('name' => $name2, 'label' => $label2, 'code' => $code2, 'flag' => $flag2))
	 */
	public function get_all(){
		$query = "SELECT * FROM language";
		return $this->db->select($query);
	}
	
	
}